package second.exception;

/**
 * @Author: heweiwei
 * @Date: 3/24/25 PM3:21
 * @Description:
 */
public class ExceptionCauseChainExample {
    public static void main(String[] args) {
        try {
            method1();
        } catch (Exception e) {
            // 打印异常堆栈信息
            e.printStackTrace();
            // 遍历异常链
            Throwable cause = e.getCause();
            while (cause != null) {
                System.out.println("Caused by: " + cause);
                cause = cause.getCause();
            }
        }
    }

    public static void method1() throws Exception {
        try {
            method2();
        } catch (ArithmeticException e) {
            // 创建一个新的异常，并将原异常作为原因
            throw new Exception("An error occurred in method1", e);
        }
    }

    public static void method2() throws ArithmeticException {
        int result = 1 / 0; // 抛出 ArithmeticException
    }
}
